/**
 * 自定义Toast弹窗组件
 * 支持成功、错误、警告、信息等多种类型
 */
import React, { useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Animated,
  Dimensions,
  Platform,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { COLORS } from '../styles/constants';

const { width } = Dimensions.get('window');

/**
 * Toast类型配置
 */
const TOAST_CONFIG = {
  success: {
    icon: 'checkmark-circle',
    color: COLORS.status.success,
    backgroundColor: COLORS.background.secondary,
  },
  error: {
    icon: 'close-circle',
    color: COLORS.status.error,
    backgroundColor: COLORS.primaryLight,
  },
  warning: {
    icon: 'warning',
    color: COLORS.status.warning,
    backgroundColor: COLORS.primaryLight,
  },
  info: {
    icon: 'information-circle',
    color: COLORS.status.info,
    backgroundColor: COLORS.background.secondary,
  },
};

/**
 * Toast组件
 * @param {Object} props
 * @param {boolean} props.visible - 是否显示
 * @param {string} props.message - 提示消息
 * @param {string} props.type - 类型：success/error/warning/info
 * @param {number} props.duration - 显示时长（毫秒）
 * @param {function} props.onHide - 隐藏回调
 */

const Toast = ({
  visible = false,
  message = '',
  type = 'success',
  duration = 2000,
  onHide = () => {},
}) => {
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const translateY = useRef(new Animated.Value(-100)).current;

  const config = TOAST_CONFIG[type] || TOAST_CONFIG.success;

  useEffect(() => {
    if (visible) {
      // 显示动画
      Animated.parallel([
        Animated.timing(fadeAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: true,
        }),
        Animated.spring(translateY, {
          toValue: 0,
          friction: 8,
          tension: 40,
          useNativeDriver: true,
        }),
      ]).start();

      // 自动隐藏
      const timer = setTimeout(() => {
        hideToast();
      }, duration);

      return () => clearTimeout(timer);
    } else {
      hideToast();
    }
  }, [visible, duration]);

  /**
   * 隐藏Toast
   */
  const hideToast = () => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }),
      Animated.timing(translateY, {
        toValue: -100,
        duration: 200,
        useNativeDriver: true,
      }),
    ]).start(() => {
      onHide();
    });
  };

  if (!visible && fadeAnim._value === 0) {
    return null;
  }

  return (
    <Animated.View
      style={[
        styles.container,
        {
          opacity: fadeAnim,
          transform: [{ translateY }],
        },
      ]}
    >
      <View
        style={[
          styles.toast,
          {
            backgroundColor: config.backgroundColor,
            borderLeftColor: config.color,
          },
        ]}
      >
        <View style={[styles.iconWrapper, { backgroundColor: config.color }]}>
          <Icon name={config.icon} size={24} color="#fff" />
        </View>
        <Text style={[styles.message, { color: config.color }]}>{message}</Text>
      </View>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: Platform.OS === 'ios' ? 60 : 40,
    left: 0,
    right: 0,
    alignItems: 'center',
    zIndex: 9999,
    paddingHorizontal: 20,
  },
  toast: {
    flexDirection: 'row',
    alignItems: 'center',
    width: width - 40,
    maxWidth: 400,
    paddingVertical: 16,
    paddingHorizontal: 16,
    borderRadius: 16,
    borderLeftWidth: 4,
    shadowColor: COLORS.shadow,
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.15,
    shadowRadius: 12,
    elevation: 8,
  },
  iconWrapper: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  message: {
    flex: 1,
    fontSize: 15,
    fontWeight: '600',
    lineHeight: 22,
  },
});

/**
 * Toast管理器
 * 提供全局Toast显示方法
 */
class ToastManager {
  static toastRef = null;

  /**
   * 设置Toast引用
   */
  static setToastRef(ref) {
    this.toastRef = ref;
  }

  /**
   * 显示成功提示
   */
  static success(message, duration = 2000) {
    this.show(message, 'success', duration);
  }

  /**
   * 显示错误提示
   */
  static error(message, duration = 2500) {
    this.show(message, 'error', duration);
  }

  /**
   * 显示警告提示
   */
  static warning(message, duration = 2000) {
    this.show(message, 'warning', duration);
  }

  /**
   * 显示信息提示
   */
  static info(message, duration = 2000) {
    this.show(message, 'info', duration);
  }

  /**
   * 显示Toast
   */
  static show(message, type = 'success', duration = 2000) {
    if (this.toastRef) {
      this.toastRef.show(message, type, duration);
    }
  }
}

/**
 * Toast容器组件
 * 用于在App根组件中渲染
 */
class ToastContainer extends React.Component {
  state = {
    visible: false,
    message: '',
    type: 'success',
    duration: 2000,
  };

  componentDidMount() {
    ToastManager.setToastRef(this);
  }

  componentWillUnmount() {
    ToastManager.setToastRef(null);
  }

  show = (message, type = 'success', duration = 2000) => {
    this.setState({
      visible: true,
      message,
      type,
      duration,
    });
  };

  hide = () => {
    this.setState({ visible: false });
  };

  render() {
    return (
      <Toast
        visible={this.state.visible}
        message={this.state.message}
        type={this.state.type}
        duration={this.state.duration}
        onHide={this.hide}
      />
    );
  }
}

export default Toast;
export { ToastManager, ToastContainer };
